# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(optparse)
library(magrittr)
library(tidyverse)
library(ggrepel)
library(extrafont)

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--pc", default = "", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)
font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))
source(str_c(scriptPath, "/fs_parse_config.R"))

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote))

configJson <- fromJSON(opt$cc)

plotConfigJson <- fromJSON(opt$pc)

pValue <- configJson$pValue %>%
  as.numeric()
useFdr <- configJson$useFdr %>%
  as.logical()
tmpFdr <- configJson$fdr %>%
  as.numeric()
fdr <- if (useFdr) {
  tmpFdr
}else 1
log2FC <- configJson$log2FC %>%
  as.numeric()

showSample <- (plotConfigJson$layout$showSample == "T")
width <- plotConfigJson$layout$width %>%
  as.numeric()
height <- plotConfigJson$layout$height %>%
  as.numeric()
up <- plotConfigJson$color$up %>%
  as.character()
down <- plotConfigJson$color$down %>%
  as.character()
none <- plotConfigJson$color$none %>%
  as.character()
xFont <- plotConfigJson$font$xFont
xTitleFont <- plotConfigJson$font$xTitleFont
yFont <- plotConfigJson$font$yFont
yTitleFont <- plotConfigJson$font$yTitleFont
mainTitle <- plotConfigJson$font$mainTitle %>%
  as.character()
mainTitleFont <- plotConfigJson$font$mainTitleFont
legendFont <- plotConfigJson$font$legendFont
legendTitle <- plotConfigJson$font$legendTitle
legendTitleFont <- plotConfigJson$font$legendTitleFont
fontFamily <- plotConfigJson$font$fontFamily
baseFamily <- fontFamily

parent <- "./"
fileName <- paste0(parent, "AllMet_Test.csv")
outFileName <- paste0(parent, "/Volcano_Plot.pdf")
data <- read_csv(fileName) %>%
  filter(is.finite(FC)) #%>%
  # filter(FC!=0)

log2FCVec <- c(log2FC, -log2FC)

logP5 <- -log(pValue)
logFdr5 <- -log(fdr)

pFilterData <- data %>%
  filter(P < pValue)

fdrFilterData <- data %>%
  filter(FDR < fdr)

useP <- if (nrow(pFilterData) < nrow(fdrFilterData)) {
  TRUE
}else FALSE

plotDataWithLog <- if (useP) {
  data %>%
    mutate(logP = -log(P))
}else {
  data %>%
    mutate(logP = -log(FDR))
}

yLabel <- if (useP) {
  "-ln(P)"
}else "-ln(FDR)"

hLineY <- if (useP) {
  logP5
}else logFdr5

hLineLabel <- if (useP) {
  str_c("P=", pValue)
}else  str_c("FDR=", fdr)

plotData <- plotDataWithLog %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    tmpLog2FC <- result[1, "log2FC"]
    q <- result[1, "FDR"]
    p <- result[1, "P"]
    col <- if (p < pValue &
      abs(tmpLog2FC) > log2FC &
      q < fdr &
      tmpLog2FC >= 0) {
      "UP"
    }else if (p < pValue &&
      abs(tmpLog2FC) > log2FC &&
      q < fdr &
      tmpLog2FC < 0) {
      "DOWN"
    }  else "NONE"
    result$col <- col
    result
  }) %>%
  mutate(col = factor(col, levels = c("UP", "DOWN", "NONE"))) %>%
  as.data.frame()

finitePlotData <- plotData %>%
  filter(is.finite(log2FC))

minX <- finitePlotData %>%
  .$log2FC %>%
  min()
maxX <- finitePlotData %>%
  .$log2FC %>%
  max()

absMaxX <- max(abs(maxX), abs(minX))
annoX <- -absMaxX
breaks <- seq(-ceiling(absMaxX), ceiling(absMaxX), 2)

upNum <- plotData %>%
  filter(col == "UP") %>%
  nrow()

downNum <- plotData %>%
  filter(col == "DOWN") %>%
  nrow()

noneNum <- plotData %>%
  filter(col == "NONE") %>%
  nrow()

pointCols <- tibble(sig = c("UP", "DOWN", "NONE"), col = c(up, down, none)) %>%
  deframe()

print(pointCols)

pointLabels <- tibble(sig = c("UP", "DOWN", "NONE"),
                      label = c(str_c("UP:", upNum), str_c("DOWN:", downNum), str_c("NONE:", noneNum))) %>%
  deframe()

textTb <- plotData %>%
  filter(Metabolite %in% plotConfigJson$layout$varNames)

p <- ggplot(plotData, mapping = aes(x = log2FC, y = logP, colour = col)) +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = xFont, vjust = 0.5),
        axis.text.y = element_text(size = yFont), legend.position = 'right',
        axis.title.y = element_text(size = yTitleFont), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = legendFont), axis.title.x = element_text(size = xTitleFont),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), legend.title = element_text(size = legendTitleFont),
        plot.title = element_text(hjust = 0.5, size = mainTitleFont, family = baseFamily)
  ) +
  ylab(yLabel) +
  ggtitle("") +
  geom_hline(aes(yintercept = hLineY), colour = "#A9A9A9", linetype = 2, size = 0.375) +
  annotate("text", x = annoX, y = hLineY + 0.1, label = hLineLabel, color = "black", vjust = 0, hjust = 0,
           size = 3, family = baseFamily) +
  geom_vline(aes(xintercept = log2FCVec[1]), colour = "#A9A9A9", linetype = 2, size = 0.3) +
  geom_vline(aes(xintercept = log2FCVec[2]), colour = "#A9A9A9", linetype = 2, size = 0.3) +
  scale_x_continuous("log2FC", breaks = breaks, limits = c(-ceiling(absMaxX), ceiling(absMaxX))) +
  geom_point(aes(), size = 2, stroke = 0)

showBorder <- plotConfigJson$layout$hasBorder %>%
  as.logical()

if (showSample) {
  if (showBorder) {
    p <- p +
      geom_label_repel(
        segment.size = 0.2,
        data = textTb, aes(x = log2FC, y = logP, label = Metabolite, color = col), size = 3, family = baseFamily,
        show.legend = F
      )
  }else {
    p <- p +
      geom_label_repel(
        segment.size = 0.2,
        data = textTb, aes(x = log2FC, y = logP, label = Metabolite, color = col), size = 3, family = baseFamily,
        label.size = NA, fill = "transparent"
      )
  }

}

if (!is.na(mainTitle)) {
  p <- p + ggtitle(mainTitle)
}

if (!is.na(legendTitle)) {
  p <- p +
    scale_colour_manual(legendTitle, values = pointCols, labels = pointLabels)
}else {
  p <- p +
    scale_colour_manual("", values = pointCols, labels = pointLabels)
}

ggsave(limitsize = FALSE, outFileName, p, width = width, height = height)





